package com.jcode222.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ExecutorConfig {

    @Value("${async.executor.core-pool-size}")
    private int corePoolSize;
    @Value("${async.executor.max-pool-size}")
    private int maximumPoolSize;
    @Value("${async.executor.keep-alive-time}")
    private int keepAliveTime;
    @Value("${async.executor.queue-capacity}")
    private int queueCapacity;
    @Value("${async.executor.thread-name-prefix}")
    private String threadNamePrefix;

    @Bean
    public Executor asyncTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maximumPoolSize);
        executor.setKeepAliveSeconds(keepAliveTime);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        executor.initialize();
        return  executor;
    }
}
